package com.twq.patternmatch.extractors

/**
 * Created by tangweiqun on 2017/11/22.
 */
object ExtractorWithLessVar {
  def main(args: Array[String]): Unit = {
    userTwiceUpper("DIDI@hotmail.com") //res0: String = match: DI in domain hotmail.com
    userTwiceUpper("DIDO@hotmail.com") //no match
    userTwiceUpper("didi@hotmail.com") //no match
  }

  //匹配一个邮箱，这个邮箱的用户名是由两个相同的大写字符串组成的
  def userTwiceUpper(s: String) = s match {
    case EMail(Twice(x@UpperCase()), domain) =>
      "match: " + x + " in domain " + domain
    case _ =>
      "no match"
  }
}

object Twice {
  def apply(s: String): String = s + s

  //如果返回一个参数的话，我们组成Option
  def unapply(s: String): Option[String] = {
    println("Twice unapply used")
    val length = s.length / 2
    val half = s.substring(0, length)
    if (half == s.substring(length)) Some(half) else None
  }
}

object UpperCase {
  //返回boolean
  def unapply(s: String): Boolean = {
    println("UpperCase unapply used")
    s.toUpperCase == s
  }
}
